<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 经纪人用户组模型类
 */
class Broker_group_model extends CI_Model
{
	public function get($groupid)
	{
		$this->db->where('groupid', $groupid);
		$result = $this->db->get('user_broker_group')->row_array();
		return $result;
	}

	public function get_all()
	{
		$this->db->order_by('groupid', 'ASC');
		$result = $this->db->get('user_broker_group')->result_array();
		return $result;
	}

	public function insert($data)
	{
		$this->db->insert('user_broker_group', $data);
		return $this->db->insert_id();
	}

	public function update($data)
	{
		if (!$data['groupid']) return;

		$this->db->where('groupid', $data['groupid']);
		$this->db->update('user_broker_group', $data);
		return $data['groupid'];
	}

	public function delete($groupid)
	{
		$this->db->where('groupid', $groupid);
		$this->db->delete('user_broker_group');
	}

	public function get_right($groupid)
	{
		$this->db->where('groupid', $groupid);
		$results = $this->db->get('user_broker_right')->result_array();

		$right = array();
		foreach ($results as $row)
		{
			if ($row['vtype'] == 'array')
			{
				$row['rvalue'] = unserialize($row['rvalue']);
			}
			$right[$row['rkey']] = $row['rvalue'];
			//更优写法
			//$right[$row['rkey']] = $row['vtype'] == 'array' ? unserialize($row['rvalue']) : $row['rvalue'];
		}

		return $right;
	}

	public function replace_right($data)
	{
		//根据权限配置文件，不存在的权限键名删除
		$this->load->config('web_right', TRUE);
		$user_right = $this->config->item('user', 'web_right');
		foreach ($data as $k => $v)
		{
			if (array_key_exists($k, $user_right) == TRUE || $k != 'groupid')
			{
				$replace['groupid'] = $data['groupid'];
				$replace['rtype'] = $user_right[$k][1];
				$replace['rkey'] = $k;
				$replace['rvalue'] = $v;
				$replace['vtype'] = $user_right[$k][0] == 'checkbox' ? 'array' : 'string';
				$this->db->replace('user_broker_right', $replace);
			}
		}
	}
}

/* End of file user_broker_model.php */
/* Location: ./application/models/user_broker_model.php */
